#include "Aircraft.h"

#include <QPainter>
#include <QKeyEvent>
#include <QBitmap>

#include "core/Core.h"

#define MOVE 5
#define NO_MOVE 0

using namespace br::org::item;

Aircraft::Aircraft() : Item()
{
    setFlags( ItemIsFocusable | ItemIsSelectable );
    setFocus();
    setSelected( true );

    utils = Utils::get();
    queueMananger = QueueMananger::get();

    image = new QImage(":img/airplane.png");

    horizontalMove = NO_MOVE;
    verticalMove = NO_MOVE;

    setType( QChar( 'a' ) );
}

Aircraft::~Aircraft()
{
    delete image;
}

QRectF Aircraft::boundingRect() const
{
    int imageWidth = image->width();
    int imageHeight = image->height();
    QPointF topLeftImage( x() - imageWidth / 2, y() - imageHeight / 2 );

    return QRectF( topLeftImage, QSizeF( imageWidth, imageHeight ) );
}

void Aircraft::paint( QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget )
{   
    Q_UNUSED( option );
    Q_UNUSED( widget );
    painter->drawImage( boundingRect(), ( *image ) );
}

void Aircraft::advance( int phase )
{
    if ( phase )
    {
        if ( horizontalMove )
        {
            setX( x() + horizontalMove );
        }
        if ( verticalMove )
        {
            setY( y() + verticalMove );
        }
        if ( horizontalMove || verticalMove )
        {
            QByteArray message = serialize();
            queueMananger->pushRequest( message );
        }
    }
}

void Aircraft::keyPressEvent( QKeyEvent* event )
{
    if ( utils->isToLeft( event ) )
    {
        horizontalMove = -MOVE;
    }
    if ( utils->isToUp( event ) )
    {
        verticalMove = -MOVE;
    }
    if ( utils->isToRight( event ) )
    {
       horizontalMove = MOVE;
    }
    if ( utils->isToDown( event ) )
    {
        verticalMove = MOVE;
    }        
}

void Aircraft::keyReleaseEvent( QKeyEvent* event )
{
    if ( utils->isHorizontalMove( event ) )
    {
        horizontalMove = NO_MOVE;
    }
    if ( utils->isVerticalMove( event ) )
    {
        verticalMove = NO_MOVE;
    }
}

void Aircraft::deserialize( const QByteArray& message )
{
    QDataStream stream( message );
    stream.setVersion( QDataStream::Qt_4_0 );

    QChar type, labelX, labelY;
    qint32 id;
    qreal valueX, valueY;
    stream >> type >> id >> labelX >> valueX >> labelY >> valueY;

    setId( id );
    setType( type );
    setX( valueX );
    setY( valueY );
}

const QByteArray Aircraft::serialize()
{
    QByteArray block;

    QDataStream out( &block, QIODevice::WriteOnly );
    out.setVersion( QDataStream::Qt_4_0 );

    out << getType();
    out << getId();
    out << QChar('x');
    out << x();
    out << QChar('y');
    out << y();

    return block;
}
